package com.azkj.album.view.activity;

import android.app.Dialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.azkj.album.R;
import com.azkj.album.adapter.ListAdapter;
import com.azkj.album.dto.CategoryBean;
import com.azkj.album.dto.ListData;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.NetworkMaster;
import com.azkj.album.network.callback.ServiceCallback;
import com.azkj.album.network.networkframe.bean.BaseResp;
import com.azkj.album.network.networkframe.net.exception.ApiException;
import com.azkj.album.network.utils.MyDateUtils;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.widgets.ChooseDateView;
import com.azkj.album.view.widgets.dialog.ColorChooseDialog;
import com.azkj.album.view.widgets.dialog.CommonDialog;
import com.azkj.album.view.widgets.dialog.DialogHelper;
import com.azkj.album.view.widgets.staggedrv.GridItemDecoration;
import com.azkj.album.view.widgets.staggedrv.StaggerdRecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity {


    @BindView(R.id.et_search)
    EditText mEtContent;

    @BindView(R.id.tv_drop_mark)
    TextView mTvDrop;

    @BindView(R.id.choose_view)
    ChooseDateView mChooseView;


    @BindView(R.id.ll_history)
    RelativeLayout mLlHistory;

    @BindView(R.id.ll_result)
    LinearLayout mLlResult;

    @BindView(R.id.mTagFlowLayout)
    TagFlowLayout mTagFlowLayout;

    @BindView(R.id.mRecyclerView)
    StaggerdRecyclerView mRecyclerView;
    @BindView(R.id.mSmartRefreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;


    @BindView(R.id.ll_delete)
    View mLlDelete;

    @BindView(R.id.tv_del_1)
    TextView tvDel1;
    @BindView(R.id.tv_del_2)
    TextView tvDel2;
    @BindView(R.id.tv_del_3)
    TextView tvDel3;
    @BindView(R.id.tv_del_4)
    TextView tvDel4;


    private ListAdapter mAdapter;

    //0，首页；1回收站；2收藏夹
    private int mPageType = 0;
    private List<CategoryBean> datas = new ArrayList<>();

    private String categoryId = "";
    private CategoryBean curCategory = new CategoryBean();

    private int mPage = 1;
    private int limit = 10;
    private String keyword = "";
    private String startDate = "";
    private String endDate = "";
    private int notifyIndex = -1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    public void initView() {
        mPageType = getIntent().getIntExtra("pageType", 0);
        initListener();
        startDate = MyDateUtils.date2String(MyDateUtils.getYearOfLater1(new Date(), -1), "yyyy-MM-dd");
        endDate = MyDateUtils.getCurrentDateStr();
        mChooseView.setHint(startDate, endDate);
        mAdapter = new ListAdapter();
        mRecyclerView.link(mAdapter, 2);
        mAdapter.bindToRecyclerView(mRecyclerView.rv);
        mAdapter.setEmptyView(R.layout.list_empty);
        mRecyclerView.addDecoration(new GridItemDecoration(this, 10));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ListData item = mAdapter.getData().get(position);
                if (mPageType == 0) {
                    Intent intent = new Intent(SearchActivity.this, DetailActivity.class);
                    intent.putExtra("detail", item);
                    intent.putExtra("fromType", DetailActivity.FROM_TYPE_MAIN);
                    startActivity(intent);
                } else if (mPageType == 1) {
                    if (mAdapter.getSelList().contains(String.valueOf(item.getId()))) {
                        mAdapter.getSelList().remove(String.valueOf(item.getId()));
                    } else {
                        mAdapter.getSelList().add(String.valueOf(item.getId()));
                    }
                    mAdapter.notifyDataSetChanged();

                    mLlDelete.setVisibility(mAdapter.getSelList().size() > 0 ? View.VISIBLE : View.GONE);

                } else {
                    notifyIndex = position;
                    Intent intent = new Intent(SearchActivity.this, DetailActivity.class);
                    intent.putExtra("detail", item);
                    intent.putExtra("fromType", DetailActivity.FROM_TYPE_COLLECT);
                    startActivity(intent);
                }
            }
        });

        //回收站
        if (mPageType == 1) {
            mAdapter.setRecovery(false);
            mSmartRefreshLayout.setEnableAutoLoadMore(false);
        }

    }

    @OnClick({R.id.iv_back, R.id.iv_history_clear, R.id.tv_drop_mark
            , R.id.iv_delete_dismiss, R.id.tv_del_1, R.id.tv_del_2, R.id.tv_del_3, R.id.tv_del_4})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_history_clear:
                ConfigStorage.getInstance().clearSearchHistory();
                setHistory();
                break;
            case R.id.tv_drop_mark:
                new ColorChooseDialog.Builder(this).setChoosetList(datas)
                        .setChooseData(curCategory)
                        .setOnClickListener((dialog, position) -> {
                            dialog.dismiss();
                            mTvDrop.setText(datas.get(position).getName());
                            curCategory = datas.get(position);
                            categoryId = datas.get(position).getId();
                            if ("-1".equals(categoryId)) {
                                categoryId = "";
                            }
                            mPage = 1;
                            getDataList();
                        }).show();
                break;

            case R.id.iv_delete_dismiss:
            case R.id.tv_del_3:

                if (mAdapter.getSelList().size() > 0) {
                    mAdapter.getSelList().clear();
                    mAdapter.notifyDataSetChanged();
                }


                mLlDelete.setVisibility(View.GONE);
                tvDel1.setVisibility(View.VISIBLE);
                tvDel2.setVisibility(View.VISIBLE);
                tvDel3.setVisibility(View.GONE);
                tvDel4.setVisibility(View.GONE);
                break;
            case R.id.tv_del_1:
                if (!mAdapter.getSelList().isEmpty()) {
                    new CommonDialog.Builder(this).setDesc("您是否彻底删除该" + mAdapter.getSelList().size() + "个图册\n" +
                                    "彻底删除后分享链接也会失效")
                            .setButton("取消", "确定")
                            .setBackground(R.mipmap.ic_login_error).
                            setOnClickListener((dialog, confirm) -> {
                                if (confirm) {
                                    deleteComplete();
                                }
                                dialog.dismiss();
                            }).show();
                }
                break;
            case R.id.tv_del_2:
                tvDel1.setVisibility(View.GONE);
                tvDel2.setVisibility(View.GONE);
                tvDel3.setVisibility(View.VISIBLE);
                tvDel4.setVisibility(View.VISIBLE);

                break;
            case R.id.tv_del_4:
                if (!mAdapter.getSelList().isEmpty()) {
                    restore();
                }
                break;
        }

    }

    private void initListener() {

        mChooseView.setOnSearchClickListener(new ChooseDateView.OnSearchListener() {
            @Override
            public void onSearchClick(String start, String end) {
                keyword = mEtContent.getText().toString().trim();
                startDate = start;
                endDate = end;
                mPage = 1;
                if (!TextUtils.isEmpty(keyword)) {
                    ConfigStorage.getInstance().saveSearchHistory(keyword);
                    setHistory();
                    getDataList();
                }
                getDataList();
            }

            @Override
            public void onReset() {
                startDate = MyDateUtils.date2String(MyDateUtils.getYearOfLater1(new Date(), -1), "yyyy-MM-dd");
                endDate = MyDateUtils.getCurrentDateStr();
                mChooseView.setHint(startDate, endDate);
                keyword = "";
                mEtContent.setText("");
                mPage = 1;
                mAdapter.setNewData(new ArrayList<>());
                mLlResult.setVisibility(View.GONE);
                mLlHistory.setVisibility(View.VISIBLE);
            }
        });

        mSmartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPage++;
                getDataList();

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPage = 1;
                getDataList();
            }
        });


        mEtContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*在软盘上点击搜索键*/
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //获取输入的内容
                    keyword = v.getText().toString();
                    if (!TextUtils.isEmpty(keyword)) {
                        ConfigStorage.getInstance().saveSearchHistory(keyword);
                        setHistory();
                        getDataList();
                    }
                }
                return false;//返回true，保留软键盘。false，隐藏软键盘
            }
        });


    }

    @Override
    public void initData() {
        setHistory();
        getCategory();

    }

    private void setHistory() {
        List<String> historyList = ConfigStorage.getInstance().getSearchHistory();

        mTagFlowLayout.setAdapter(new TagAdapter<String>(historyList) {
            @Override
            public View getView(FlowLayout parent, int position, String history) {

                TextView tv = (TextView) getLayoutInflater().inflate(R.layout.layout_tag_view,
                        mTagFlowLayout, false);
                tv.setText(history);
                return tv;
            }
        });

        mTagFlowLayout.setOnTagClickListener((view, posi, parent) -> {
            mPage = 1;
            keyword = historyList.get(posi);
            mEtContent.setText(keyword);
            mEtContent.setSelection(keyword.length());
            getDataList();
            return true;
        });


    }


    @Override
    protected void initPresenter() {

    }

    private void getCategory() {
        NetworkMaster.getInstance().getCommonService().mainCategory(new ServiceCallback<BaseResp<List<CategoryBean>>>() {
            @Override
            public void onSuccess(BaseResp<List<CategoryBean>> jsonObj) {
                curCategory = new CategoryBean();
                curCategory.setId("-1");
                curCategory.setName("全部");
                datas.add(curCategory);
                datas.addAll(jsonObj.getData());
            }

            @Override
            public void onError(ApiException apiException) {
                ToastUtils.showCenterToast(apiException.errorInfo.error);
            }
        });
    }

    public void getDataList() {
        DialogHelper.showLoadingDialog();
        mLlResult.setVisibility(View.VISIBLE);
        mLlHistory.setVisibility(View.GONE);
        if (mPageType == 0) {

            NetworkMaster.getInstance().getCommonService().getList(ConfigStorage.getInstance().getToken(),
                    String.valueOf(mPage), String.valueOf(limit), keyword, categoryId, startDate, endDate, new ServiceCallback<BaseResp<List<ListData>>>() {
                        @Override
                        public void onSuccess(BaseResp data) {
                            DialogHelper.hideDialog();
                            mSmartRefreshLayout.finishLoadMore(true);
                            mSmartRefreshLayout.finishRefresh(true);
                            if (data.getCode() == 1) {
                                List<ListData> list = (List<ListData>) data.getData();
                                if (mPage == 1) {
                                    mAdapter.setNewData(list);
                                } else {
                                    mAdapter.addData(list);
                                }
                                //处理数据
                                if (list.size() < limit) {

                                    mSmartRefreshLayout.setEnableLoadMore(false);
                                } else {

                                    mSmartRefreshLayout.setEnableLoadMore(true);
                                }
                            } else {
                                ToastUtils.showCenterToast(data.getMsg());
                            }
                        }

                        @Override
                        public void onError(ApiException apiException) {
                            DialogHelper.hideDialog();
                            mSmartRefreshLayout.finishLoadMore(true);
                            mSmartRefreshLayout.finishRefresh(true);
                            ToastUtils.showCenterToast(apiException.errorInfo.error);
                        }

                    });
        } else if (mPageType == 1) {
            NetworkMaster.getInstance().getCommonService().listRecycle(ConfigStorage.getInstance().getToken(),
                    String.valueOf(mPage), keyword, categoryId,
                    startDate, endDate,
                    new ServiceCallback<BaseResp<List<ListData>>>() {
                        @Override
                        public void onSuccess(BaseResp data) {
                            DialogHelper.hideDialog();
                            mSmartRefreshLayout.finishLoadMore(true);
                            mSmartRefreshLayout.finishRefresh(true);
                            if (data.getCode() == 1) {
                                List<ListData> list = (List<ListData>) data.getData();
                                if (mPage == 1) {
                                    mAdapter.setNewData(list);
                                } else {
                                    mAdapter.addData(list);
                                }
                                //处理数据
                                if (list.size() < 10) {
                                    mSmartRefreshLayout.setEnableLoadMore(false);
                                } else {
                                    mSmartRefreshLayout.setEnableLoadMore(true);
                                }
                            } else {
                                ToastUtils.showCenterToast(data.getMsg());
                            }

                        }

                        @Override
                        public void onError(ApiException apiException) {
                            DialogHelper.hideDialog();
                            mSmartRefreshLayout.finishLoadMore(true);
                            mSmartRefreshLayout.finishRefresh(true);
                            ToastUtils.showCenterToast(apiException.errorInfo.error);
                        }
                    });
        } else {
            NetworkMaster.getInstance().getCommonService().mainCollectList(keyword,
                    String.valueOf(mPage), startDate, endDate, new ServiceCallback<BaseResp<List<ListData>>>() {
                        @Override
                        public void onSuccess(BaseResp data) {
                            DialogHelper.hideDialog();
                            mSmartRefreshLayout.finishLoadMore(true);
                            mSmartRefreshLayout.finishRefresh(true);
                            if (data.getCode() == 1) {
                                List<ListData> list = (List<ListData>) data.getData();
                                if (mPage == 1) {
                                    mAdapter.setNewData(list);
                                } else {
                                    mAdapter.addData(list);
                                }
                                //处理数据
                                if (list.size() < 10) {
                                    mSmartRefreshLayout.setEnableLoadMore(false);
                                } else {
                                    mSmartRefreshLayout.setEnableLoadMore(true);
                                }
                            } else {
                                ToastUtils.showCenterToast(data.getMsg());
                            }
                        }

                        @Override
                        public void onError(ApiException apiException) {
                            DialogHelper.hideDialog();
                            mSmartRefreshLayout.finishLoadMore(true);
                            mSmartRefreshLayout.finishRefresh(true);
                            ToastUtils.showCenterToast(apiException.errorInfo.error);
                        }

                    });
        }
    }

    private void deleteComplete() {
        StringBuilder idsSb = new StringBuilder();
        for (String id : mAdapter.getSelList()) {
            idsSb.append(id + ",");
        }
        NetworkMaster.getInstance().getCommonService().delComplete(ConfigStorage.getInstance().getToken(), idsSb.toString(), new ServiceCallback() {
            @Override
            public void onSuccess(Object jsonObj) {
                for (String id : mAdapter.getSelList()) {
                    ListData item = mAdapter.getItemById(id);
                    int position = mAdapter.getItemPosition(item);
                    mAdapter.notifyItemRemoved(position);
                    mAdapter.getData().remove(item);
                }
                mAdapter.getSelList().clear();
                mLlDelete.setVisibility(View.GONE);
                tvDel1.setVisibility(View.VISIBLE);
                tvDel2.setVisibility(View.VISIBLE);
                tvDel3.setVisibility(View.GONE);
                tvDel4.setVisibility(View.GONE);
            }

            @Override
            public void onError(ApiException apiException) {
                ToastUtils.showCenterToast(apiException.errorInfo.error);
            }
        });
    }

    private void restore() {
        StringBuilder idsSb = new StringBuilder();
        for (String id : mAdapter.getSelList()) {
            idsSb.append(id + ",");
        }
        NetworkMaster.getInstance().getCommonService().restore(ConfigStorage.getInstance().getToken(), idsSb.toString(), new ServiceCallback() {
            @Override
            public void onSuccess(Object jsonObj) {
                for (String id : mAdapter.getSelList()) {
                    ListData item = mAdapter.getItemById(id);
                    int position = mAdapter.getItemPosition(item);
                    mAdapter.notifyItemRemoved(position);
                    mAdapter.getData().remove(item);
                }
                mAdapter.getSelList().clear();
                EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_MAIN_RECOVERY));
                ToastUtils.showCenterToast("恢复成功，请在首页查看。");
                mLlDelete.setVisibility(View.GONE);
                tvDel1.setVisibility(View.VISIBLE);
                tvDel2.setVisibility(View.VISIBLE);
                tvDel3.setVisibility(View.GONE);
                tvDel4.setVisibility(View.GONE);

            }

            @Override
            public void onError(ApiException apiException) {
                ToastUtils.showCenterToast(apiException.errorInfo.error);
            }
        });
    }

    @Subscribe
    public void onMessage(MessageEvent messageEvent) {
        super.onMessage(messageEvent);
        switch (messageEvent.getType()) {
            case MessageType.TYPE_ON_DETAIL_DEL:
                if (null != mAdapter && -1 != notifyIndex) {
                    mAdapter.remove(notifyIndex);
                    notifyIndex = -1;
                }
                EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_COLLECT_CANCEL));
                break;
        }

    }

}
